package com.example.wzh.rxdemo.rx;

import android.annotation.SuppressLint;

import com.example.wzh.rxdemo.LogTag;
import com.wzh.advancelog.log.WzhLog;

import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.functions.Function;

public class RetryFunction implements Function<Observable<Throwable>, ObservableSource<?>> {

        @Override
        public ObservableSource<?> apply(Observable<Throwable> throwableObservable) {
            return throwableObservable.flatMap(new Function<Throwable, ObservableSource<?>>() {
                int retryCount = -1;
                final long[] retryDurations = {1, 3, 5, 7, 9};

                @SuppressLint("DefaultLocale")
                @Override
                public ObservableSource<?> apply(Throwable throwable) {
                    retryCount++;
                    if (retryCount < retryDurations.length) {
                        WzhLog.i(LogTag.TAG_WZH, String.format("第%d次重试,%d秒后开始", retryCount + 1, retryDurations[retryCount]));
                        return Observable.timer(retryDurations[retryCount], TimeUnit.SECONDS);
                    } else {
                        return Observable.error(throwable);
                    }
                }
            });
        }
    }